<template>
  <div class="dashboard-container">

    <el-card shadow="never" class="custom-card" :body-style="{ padding: '0px' }">
      <div class="centered-container">
        <el-row class="centered-row">
          <!-- el-input -->
          <el-col :span="24" class="input-col" style="margin-top: 12px">
            <el-input
              v-model="input"
              :style="{ width: 'auto', minWidth:'500px',minHeight: '50px' }"
              placeholder="多个关键字用空格隔开"
              clearable
            >
              <template #append>
                <el-button
                  icon="Search"
                  type="primary"
                  :style="{ backgroundColor: 'var(--el-color-primary)', minHeight: '50px', color: 'white' }"
                  @click="handleSpuPageQuery"
                >
                  搜索
                </el-button>
              </template>
            </el-input>
          </el-col>

          <!-- 显示第一层 -->
          <el-col :span="24" class="radio-col">
            <el-radio-group v-model="topCategory" size="large" @click="showNumber=2">
              <!-- 添加全部按钮 -->
              <el-radio-button label="">首页</el-radio-button>
              <el-radio-button
                v-for="category in categoryOptions"
                :key="category.value"
                :label="category.value"
              >
                {{ category.label }}
              </el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card shadow="never" v-if="showNumber === 2">
      <el-row class="centered-row">
        <!-- 显示第二层 -->
        <el-col :span="24" class="radio-col">
          <el-radio-group v-model="subCategory" class="spaced-radio-group">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button
              v-for="sub in currentSubCategories"
              :key="sub.value"
              :label="sub.value"
            >
              {{ sub.label }}
            </el-radio-button>
          </el-radio-group>
        </el-col>
      </el-row>

      <!-- 替换表格为卡片布局 -->
      <div class="card-container" style="border: 1px solid rgba(165,165,165,0.63)">
        <el-row :gutter="20">
          <el-col
            v-for="item in pageData"
            :key="item.id"
            :xs="12" :sm="8" :md="6" :lg="4"
            class="card-col"
          >
            <el-card
              shadow="hover"
              class="product-card"
              @click="handleCardClick(item)"
            >
              <template #footer>
                <div class="card-header">
                  <div class="spu-name">{{ item.spuName }}</div>
                </div>
              </template>
              <el-image
                :src="item.mainImage"
                fit="cover"
                class="preview-image"
              />
            </el-card>
          </el-col>
        </el-row>
      </div>
      <!-- 分页组件 -->
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleSpuPageQuery()"
      />
    </el-card>

    <el-card shadow="never"  v-if="showNumber === 3" v-loading="loading">

      <el-row :gutter="20" v-loading="loading">
        <el-col :span="6">
          <el-card
            shadow="hover"
            class="product-card"
          >
            <el-image
              :src="currentMainImage"
              fit="cover"
              class="preview-image"
            />
          </el-card>
        </el-col>
        <el-col :span="18">
          <div class="spu-name" style="font-weight: bold">{{ spu? spu.spuName : '' }}</div>
          <div style="background-color: rgba(165,165,165,0.25); padding: 10px">
            <el-row :gutter="40">
              <el-col :span="24">
                <div style="display: flex;align-items: flex-start;">
                  <div style="white-space: nowrap;">规格描述</div>
                  <div style="margin-left: 20px">{{ spu? spu.description : ''}}</div>
                </div>

              </el-col>
              <el-col :span="24">
                <div style="display: flex;align-items: flex-end;">
                  <div>参考价格</div>
                  <div style="margin-left: 20px;color: #409eff;font-size: 35px">￥{{ currentPrice }}</div>
                </div>

              </el-col>
            </el-row>

          </div>
          <el-col :span="24">
            <!-- SKU规格选择区域 -->
            <el-row style="margin-top: 20px;">
              <el-col :span="24">
                <div v-for="group in specGroups" :key="group.specGroupForm.id" class="spec-group"
                     style="display: flex;align-items: center">
                  <div>{{ group.specGroupForm.groupName }}</div>
                  <div style="display: flex;align-items: start; margin-left: 20px">
                    <el-radio-group
                      v-model="selectedSpecValues[group.specGroupForm.id]"
                      @change="handleSpecChange" class="spaced-radio-group"
                    >
                      <el-radio-button
                        v-for="value in group.specValueForms"
                        :key="value.id"
                        :label="value.id"
                        :disabled="disabledSpecValues[group.specGroupForm.id]?.has(value.id)"
                        @click="handleSpecValueClick(group.specGroupForm.id, value.id)"
                      >
                        {{ value.valueName }}
                      </el-radio-button>
                    </el-radio-group>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <div style="display: flex;align-items: center;">
              <div>数量</div>
              <div style="margin-left: 48px;display: flex; align-items: flex-end;gap: 10px; ">
                <el-input v-model="countResult" :style="{width: '60px'}" disabled></el-input>
                <el-input-number v-model="count" :min="1" />
                {{ currentSku ? currentSku.skuMeasurement : "" }}
              </div>
            </div>
          </el-col>

          <el-col :span="24" style="margin-top: 40px">
            <div style="display: flex;align-items: center;">
              <el-button type="warning"  @click="handleAddCart">加入购物车</el-button>
              <el-button type="danger">购物车结算</el-button>
            </div>
          </el-col>
        </el-col>

      </el-row>

      <el-row style="background-color: rgba(165,165,165,0.13);">
        <el-col :span="24">
          <div class="spu-name" style="color: #409eff;height: 40px;font-weight: bolder;border-top: 2px solid #409eff;width: 200px;text-align: center;display: flex; justify-content: center; align-items: center;">宝贝详情</div>
        </el-col>
      </el-row>
      <el-row :gutter="0" justify="center" align="middle" :style="{marginRight:'5px',marginLeft:'5px'}">
        <el-col
          v-for="(src, index) in currentDetailImages"
          :key="index"
          :xs="24"
        >
          <el-image
            :src="src"
            :fit="'cover'"
            style="width: 100%; height: auto;"
          />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import ProductSpuAPI, { ProductSpuPageQuery, ProductSpuPageVO } from "@/api/spu/product-spu";
import ProductSkuAPI, { ProductSkuForm, SPKGV, SpuSkuSpecGroupSpecValueVo } from "@/api/sku/product-sku";
import OrderAPI, { OrderForm } from "@/api/myflow/order/order";
import OrderItemAPI, { OrderItemForm } from "@/api/myflow/order/order-item";

defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});
const showNumber = ref<number>(2);
const input = ref("");
const topCategory = ref(""); // 第一层选中的分类ID
const subCategory = ref(""); // 第二层选中的子分类ID
const categoryOptions = ref<any[]>([]); // 存储分类选项
const count = ref<number>(1);
const countResult = ref<number>(1);
watch(count, () => {
  if (currentSku.value !== null && currentSku.value?.skuRatio) {
    countResult.value = count.value * currentSku.value.skuRatio;
  }
});
// 获取所有第二层分类（顶级分类的直接子分类）
const allSecondLevelCategories = computed(() => {
  return categoryOptions.value.flatMap(
    topCategory => topCategory.children || [],
  );
});
// 计算当前显示的子分类
const currentSubCategories = computed(() => {

  if (topCategory.value === "") {
    // 选择了"首页"，显示所有第二层分类
    return allSecondLevelCategories.value;
  } else {
    // 选择了具体分类，显示该分类的子分类
    const selectedCategory = categoryOptions.value.find(
      cat => cat.value === topCategory.value,
    );
    return selectedCategory?.children || [];
  }
});
async function initCategoryOptions() {
  try {
    const response = await ProductSpuAPI.getProductCategoryOptions();
    if (response) {
      // 直接使用返回的数据，不再包装顶级分类
      categoryOptions.value = response;
    }
  } catch (error) {
    console.error("获取分类选项失败:", error);
  }
}

// 当顶级分类变化时重置子分类选择
topCategory.value = "";
subCategory.value = "";
const queryParams = reactive<ProductSpuPageQuery>({
  pageNum: 1,
  pageSize: 10,
  status: 1,
});
const loading = ref(false);
const pageData = ref<ProductSpuPageVO[]>([]);
const total = ref(0);

function handleSpuPageQuery() {
  showNumber.value = 2;
  loading.value = true;
  ProductSpuAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

const spu = ref<ProductSpuPageVO>();

const jsonToArray = (jsonStr: string | undefined): string[] => {
  if (!jsonStr || jsonStr.trim() === "") return [];

  try {
    const parsed = JSON.parse(jsonStr);
    // 处理两种可能的格式：
    // 1. 完整格式: { detailImages: [...] }
    // 2. 简单数组格式: [...] (兼容旧格式)
    if (parsed && parsed.detailImages) {
      return Array.isArray(parsed.detailImages) ? parsed.detailImages : [];
    }
    return Array.isArray(parsed) ? parsed : [];
  } catch (e) {
    console.error("JSON 解析错误", e);
    return [];
  }
};

const selectedSpecValues = ref<Record<string, number | string>>({});

const allSkuData = ref<SpuSkuSpecGroupSpecValueVo[]>([]);
const skuSpecValues = ref<Record<string, any[]>>({});
const specGroups = ref<any[]>([]);
const currentSku = ref<ProductSkuForm | null>(null);

// 计算当前显示的主图
const currentMainImage = computed(() => {
  return currentSku.value?.mainImage || spu.value?.mainImage || "";
});

// 计算当前显示的详情图
const currentDetailImages = computed(() => {
  if (currentSku.value?.detailImages) {
    return jsonToArray(currentSku.value.detailImages);
  } else if (spu.value?.detailImages) {
    return jsonToArray(spu.value.detailImages);
  }
  return [];
});

// 计算当前价格
const currentPrice = computed(() => {
  return currentSku.value?.price || spu.value?.price || 0;
});
// 修改规格值选择处理函数
const handleSpecValueClick = (groupId: string, valueId: number) => {
  // 检查当前规格值是否被禁用
  if (disabledSpecValues.value[groupId]?.has(valueId)) {
    return; // 如果禁用，直接返回
  }
  const currentValue = selectedSpecValues.value[groupId];

  // 如果当前组已选中该值，则取消选中（反选）
  if (currentValue === valueId) {
    selectedSpecValues.value[groupId] = "";
  }
  // 否则选中该值
  else {
    selectedSpecValues.value[groupId] = valueId;
  }

  // 触发规格变化处理
  handleSpecChange();
};
// 计算不可用的规格值（没有对应SKU的规格值）
const disabledSpecValues = computed(() => {
  const disabledMap: Record<string, Set<number>> = {};

  // 初始化禁用映射
  specGroups.value.forEach(group => {
    const groupId = group.specGroupForm.id;
    disabledMap[groupId] = new Set();
  });
  //


  // 遍历所有可能的规格组合
  specGroups.value.forEach(group => {
    const groupId = group.specGroupForm.id;

    group.specValueForms.forEach(value => {
      // 临时设置选中当前规格值
      const tempSelected = { ...selectedSpecValues.value, [groupId]: value.id };

      // 获取所有选中的规格值ID
      const selectedValueIds = Object.values(tempSelected)
        .filter(id => id !== "") as number[];

      // 检查是否存在匹配的SKU
      const hasMatch = allSkuData.value.some(sku => {
        const skuId = sku.skuForm?.id?.toString();
        if (!skuId || !skuSpecValues.value[skuId]) return false;

        const skuValueIds = skuSpecValues.value[skuId].map(item => item.specValueId);
        return selectedValueIds.every(id => skuValueIds.includes(id));
      });

      // 如果没有匹配的SKU，则禁用该规格值
      if (!hasMatch) {
        disabledMap[groupId].add(value.id);
      }
    });
  });

  return disabledMap;
});
// 规格变化处理
const handleSpecChange = () => {
  // 检查是否所有规格组都选择了值
  const allSelected = specGroups.value.every(
    group => selectedSpecValues.value[group.specGroupForm.id] !== undefined,
  );

  if (!allSelected) {
    currentSku.value = null;
    return;
  }

  // 获取当前选中的所有规格值ID
  const selectedValueIds = Object.values(selectedSpecValues.value);

  // 查找匹配的SKU
  const matchedSku = allSkuData.value.find(sku => {
    const skuId = sku.skuForm?.id?.toString();
    if (!skuId || !skuSpecValues.value[skuId]) return false;

    // 获取当前SKU关联的规格值ID
    const skuValueIds = skuSpecValues.value[skuId].map(item => item.specValueId);

    // 检查是否所有选中的规格值都在当前SKU中
    return selectedValueIds.every(id => skuValueIds.includes(id.toString()));
  });

  if (matchedSku && matchedSku.skuForm !== undefined) {
    currentSku.value = matchedSku.skuForm;
    // ElMessage.success("已选择规格");
  } else {
    currentSku.value = null;
  }
};

const spkgvData = ref<SPKGV>({
  all: [],  // 默认值为空数组
  sv: [],    // 默认值为空数组
});
// 添加处理卡片点击的方法
const handleCardClick = (item: ProductSpuPageVO) => {
  showNumber.value = 3;
  console.log("点击的商品对象:", item);
  spu.value = item;

  ProductSkuAPI.getListSpuSkuSpecGroupSpecValueVo(item.id).then((response) => {
    console.log(response);
    spkgvData.value = response;
    console.log(spkgvData.value);
// 处理新的数据结构
    allSkuData.value = spkgvData.value?.all || [];
    console.log(allSkuData);
    skuSpecValues.value = {};
    // 处理规格值关联数据
    if (spkgvData.value.sv) {
      spkgvData.value.sv.forEach((item: any) => {
        if (item.skuId) {
          skuSpecValues.value[item.skuId] = item.specValues || [];
        }
      });
    }
    console.log(skuSpecValues);
    // 提取规格组信息
    if (allSkuData.value.length > 0 && allSkuData.value[0].specGroupValueVoList) {
      specGroups.value = allSkuData.value[0].specGroupValueVoList;
    }

    // 重置选择
    selectedSpecValues.value = {};
    currentSku.value = null;
    // 优化：尝试找到第一个有效的SKU组合作为默认选择
    let foundValidSku = false;
    // 1. 尝试使用当前规格组中的第一个有效组合
    if (specGroups.value.length > 0) {
      // 尝试找到一个有效的SKU组合
      for (const skuData of allSkuData.value) {
        const skuId = skuData.skuForm?.id?.toString();
        if (skuId && skuSpecValues.value[skuId] && skuSpecValues.value[skuId].length > 0) {
          // 使用这个SKU的规格值来设置选中的规格值
          skuSpecValues.value[skuId].forEach(specValue => {
            selectedSpecValues.value[specValue.specGroupId] = specValue.specValueId;
          });
          foundValidSku = true;
          break; // 找到第一个有效的SKU后就退出循环
        }
      }
    }

    // 2. 如果没有找到有效的SKU，回退到每个规格组选择第一个规格值
    if (!foundValidSku && specGroups.value.length > 0) {
      specGroups.value.forEach(group => {
        if (group.specValueForms && group.specValueForms.length > 0) {
          selectedSpecValues.value[group.specGroupForm.id] = group.specValueForms[0].id;
        }
      });
    }
// 尝试匹配默认选择的规格
    setTimeout(handleSpecChange, 100);
  });


};
const orderData = reactive<OrderForm>({});

const addItem = reactive<OrderItemForm>({});
function handleAddCart() {
  loading.value = true;
  OrderAPI.getCartOrderFormByUser().then((data) => {
    Object.assign(orderData,data);
    addItem.quantity = countResult.value;
    addItem.skuId = currentSku.value?.id;
    addItem.orderId = orderData.id;
    addItem.productName = spu.value.spuName;
    OrderItemAPI.addItemToCart(addItem).then(()=> {

      ElMessage({
        // customClass: 'center-message',
        duration: 6000,
        message: '添加购物车成功',
        type: 'success',
        plain: true,
      })
    })
  }).finally(() => {
    loading.value = false;
  });

}
onMounted(() => {
  initCategoryOptions();
  handleSpuPageQuery();
});

</script>

<style lang="scss">
/* 原有样式保持不变 */
.dashboard-container {
  position: relative;
  padding: 12px;

  .el-radio-button__inner {
    border-radius: 10px;
  }

  .el-radio-button__inner--checked {
    font-weight: bold;
  }

  .spaced-radio-group {
    display: flex;
    flex-wrap: wrap;
    justify-content: start;
    gap: 12px;

    :deep(.el-radio-button) {
      flex: 0 0 auto; /* 自适应宽度 */
      margin: 4px; /* 额外边距保证视觉平衡 */
      // 默认状态 - 无边框
      .el-radio-button__inner {
        border: none;
        background-color: transparent;
        color: #606266; // 默认文字颜色
        padding: 8px 16px;
        transition: all 0.3s ease;
      }

      // 悬停状态
      &:hover .el-radio-button__inner {
        color: #f56c6c; // 悬停时文字颜色
      }

      // 选中状态
      &.is-active .el-radio-button__inner {
        color: #f56c6c; // 红色文字
        border-radius: 10px;
        border: 1px solid #f56c6c; // 红色边框
        background-color: transparent;
        box-shadow: none;
        font-weight: bold;
      }
    }
  }

  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }

  .version-item {
    padding: 16px;
    margin-bottom: 12px;
    background: var(--el-fill-color-lighter);
    border-radius: 8px;
    transition: all 0.2s;

    &.latest-item {
      background: var(--el-color-primary-light-9);
      border: 1px solid var(--el-color-primary-light-5);
    }

    &:hover {
      transform: translateX(5px);
    }

    .version-content {
      margin-bottom: 12px;
      line-height: 1.5;
      color: var(--el-text-color-secondary);
    }
  }


  .centered-row {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
  }


  .el-input {
    width: 100%; /* Ensure input spans the full width */
  }

  .el-radio-group {
    display: flex;
    justify-content: center;
  }

  /* 自定义卡片样式 */
  .custom-card {
    position: relative;
    border: none !important; /* 移除默认边框 */
    border-radius: 4px 4px 0 0; /* 仅保留顶部圆角 */
  }

  /* 底部伪元素实现彩色边框 */
  .custom-card::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 3px; /* 边框粗细 */
    background-color: var(--el-color-primary); /* primary颜色 */
    border-radius: 0 0 4px 4px; /* 底部圆角 */
  }

  /* 布局调整 */
  .centered-container {
    padding-bottom: 0 !important; /* 移除底部内边距 */
  }


  .radio-col {
    margin-top: auto; /* 将单选组推到底部 */
    padding-top: 12px; /* 与上方内容保持间距 */
  }

  .preview-image {

    cursor: zoom-in;
    border-radius: 4px;
    object-fit: cover;
    transition: all 0.3s;
  }

  .preview-image:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .product-card {
    height: 100%;
    display: flex;
    flex-direction: column;
    cursor: pointer;
    transition: transform 0.3s, box-shadow 0.3s;
  }

  .product-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .image {
    width: 100%;
    height: auto;
    max-width: 400px; /* 控制最大宽度，保持等宽 */
  }

  /* 添加更明显的禁用状态样式 */
  :deep(.el-radio-button.is-disabled) {
    opacity: 0.5;
    cursor: not-allowed;

    .el-radio-button__inner {
      position: relative;
      text-decoration: line-through;

      &::after {
        content: "×";
        position: absolute;
        top: 0;
        right: 5px;
        color: #f56c6c;
      }
    }
  }

  /* 添加悬停效果（仅对可用项） */
  :deep(.el-radio-button:not(.is-disabled)) {
    &:hover .el-radio-button__inner {
      transform: scale(1.05);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      border-color: #f56c6c;
    }
  }

  .spec-group {
    margin-bottom: 20px;
  }

  .spec-group-name {
    margin-bottom: 10px;
  }

  .spec-values {
    :deep(.el-radio-button) {
      margin-right: 10px;
      margin-bottom: 10px;

      .el-radio-button__inner {
        border-radius: 4px;
        border: 1px solid #DCDFE6;
        padding: 10px 16px;
      }

      &.is-active {
        .el-radio-button__inner {
          box-shadow: none;
        }
      }
    }
  }

  .quantity-selector {
    display: flex;
    align-items: center;
  }

  /* 新增样式 */
  .spec-title {
    font-weight: bold;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
  }
}

/* 添加全局样式 */
.center-message {
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  min-width: 120px;
  text-align: center;
  border-radius: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(2px);
}
</style>
